package com.example.wechatdaka.utils;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author panlx
 * @version 1.0
 * @date 2020-10-02 20:14
 */
public class SendCode {
//    获取用户微信openID
    public String getOpenId(String code){
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 参数
        URI uri = null;
        JSONObject json = new JSONObject();
        try {
            // 将参数放入键值对类NameValuePair中,再放入集合中
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("appid", "wxefa954beafc85d6c"));
//            下方是线上的
//            params.add(new BasicNameValuePair("appid", "wxcd50eea455e10818"));
            System.out.println(params);
            params.add(new BasicNameValuePair("secret", "5a16b5c3c9186732b816cd8e8ca8966b"));
//            下方线上
//            params.add(new BasicNameValuePair("secret", "c008e2d6883f112e4bed1d6b31878a7c"));
            System.out.println(params);
            params.add(new BasicNameValuePair("js_code", code));
            System.out.println(params);
            params.add(new BasicNameValuePair("grant_type", "authorization_code"));
            System.out.println(params);
            // 设置uri信息,并将参数集合放入uri;
            // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
            uri = new URIBuilder().setScheme("https").setHost("api.weixin.qq.com")
//                    .setPort(12345)
                    .setPath("/sns/jscode2session")
                    .setParameters(params).build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);
        System.out.println(httpGet);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println(responseEntity);
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                String res= EntityUtils.toString(responseEntity);
                System.out.println("响应内容为:" + res);

                JSONObject jsonObject = JSONObject.fromObject(res);
                //Iterator ite = jsonObject.keys();
                // 遍历jsonObject数据,添加到Map对象
                String data = jsonObject.get("openid").toString();

                return data;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "error";
    }

    }

